#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "file.h"

/** Prepare an filesystem image use dd,mkfs tool:
 * step 1. dd if=/dev/zero of=file1.img bs=1M count=500
 * step 2. mkfs.ext2 file1.img
 * step 3. mount file1.img file1 -o loop
 */
#define FILE_DEV "/mnt/lzhong/media/file.img"

static int file_dev_exist(char *dev)
{
	if(dev == NULL)
		return 0;

	if(access(dev,F_OK)<0)
		return 0;
	else
		return 1;
}
static int file_dev_mount(char *dev,char *mpoint,char *options)
{
	if(dev == NULL || mpoint == NULL)
		return -1;
	char cmd[64]={0};

	sprintf(cmd,"sudo mount %s %s ",FILE_DEV,mpoint);
	if(options != NULL)
		strcat(cmd,options);

	puts(cmd);
	if(system(cmd)!=0)
		return -1;
	else
		return 0;
}
static int file_dev_umount(char *mpoint,char *options)
{
	if(mpoint == NULL)
		return -1;
	char cmd[64]={0};
	sprintf(cmd,"sudo umount %s ",mpoint);
	if(options != NULL)
		strcat(cmd,options);

	puts(cmd);
	if(system(cmd)!=0)
		return -1;
	else
		return 0;
}
static int file_dev_format(char *dev,char *options)
{
	if(dev == NULL)
		return -1;

	char cmd[64]={0};
	sprintf(cmd,"mkfs %s",FILE_DEV);
	if(options != NULL)
		strcat(cmd,options);

	puts(cmd);
	if(system(cmd)!=0)
		return -1;
	else
		return 0;
}

static int file_dir_filter(st_rsc_content_unit *dir)
{
	if(dir->type != CONT_TYPE_DIR)
		return 0;
	if(strlen(dir->name)!=strlen("20140206"))
		return 0;
	int i = 0;
	for(i = 0;i < strlen(dir->name);i++)
	{
		if(dir->name[i]<'0' || dir->name[i]>'9')
			return 0;
	}

	return 1;
}
static int file_file_filter(st_rsc_content_unit *file)
{
	if(file->type != CONT_TYPE_FILE)
		return 0;
	int len = strlen(file->name);
#if 0
	int file_fix_len = strlen("142900_04.avi");

	if(len != file_fix_len)
		return 0;
	else if(strcmp(file->name+len-4,".avi"))
		return 0;

	int i = 0;
	for(i = 0;i < 6;i++)
	{
		if(file->name[i]<'0' || file->name[i]>'9')
			return 0;
	}

#else
	if(strcmp(file->name+len-4,".avi")) /// filter all .avi file.
		return 0;
#endif

	return 1;
}

static st_rsc_dev_meta file_dev_meta = 
{
	.type = DEV_TYPE_FILE,
	.max_num = 1,
	.mpoint = "/mnt/lzhong/media",
	.exist = file_dev_exist,
	.mount = file_dev_mount,
	.umount = file_dev_umount,
	.format = file_dev_format,
};
static st_rsc_content_meta file_cont_meta = 
{
	.dir_filter[CONT_DATA_REC] = file_dir_filter,
	.dir_filter[CONT_DATA_VIDEO] = NULL,
	.dir_filter[CONT_DATA_AUDIO] = NULL,
	.dir_filter[CONT_DATA_PICTURE] = NULL,
	.dir_filter[CONT_DATA_ALARM] = NULL,
	.dir_filter[CONT_DATA_ALL] = file_dir_filter,

	.file_filter[CONT_DATA_REC] = file_file_filter,
	.file_filter[CONT_DATA_VIDEO] = NULL,
	.file_filter[CONT_DATA_AUDIO] = NULL,
	.file_filter[CONT_DATA_PICTURE] = NULL,
	.file_filter[CONT_DATA_ALARM] = NULL,
	.file_filter[CONT_DATA_ALL] = file_file_filter,
};

struct storage_dev_meta *rsc_file_dev_meta = &file_dev_meta;
struct storage_content_meta *rsc_file_cont_meta = &file_cont_meta;

